def process_file(dst):     # 读文件到缓冲区
    try:     # 打开文件
        file = open(dst, 'r')  # dst为文本的目录路径
    except IOError as s:
        print (s)
        return None
    try:     # 读文件到缓冲区
        bvffer = file.read()
    except:
        print ("Read File Error!")
        return None
    file.close()
    return bvffer
def process_buffer(bvffer):
    if bvffer:
        word_freq = {}
        # 下面添加处理缓冲区 bvffer代码，统计每个单词的频率，存放在字典word_freq
        # 将文本内容都改为小写
        bvffer = bvffer.lower()
        #去除文本中的中英文标点符号
        for ch in '“‘!;,.?”':
            bvffer = bvffer.replace(ch, " ")
        # strip()删除空白符（包括'/n', '/r','/t'）；split()以空格分割字符串
        words = bvffer.strip().split()
        for word in words:
            word_freq[word] = word_freq.get(word, 0) + 1
        return word_freq

def output_result(word_freq):
    if word_freq:
        sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
        for item in sorted_word_freq[:10]:  # 输出 Top 10 的单词
            print (item)

if __name__ == "__main__":
    import argparse
    dst = "D:\work\wordcount\Gone_with_the_wind.txt"
    bvffer = process_file(dst)
    word_freq = process_buffer(bvffer)
    output_result(word_freq)
